package org.hiucung.orangemusic;

import android.app.ActivityOptions;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.transition.Slide;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.hiucung.orangemusic.bean.MusicBean;
import org.hiucung.orangemusic.dialog.MusicListBottomDialog;
import org.hiucung.orangemusic.helper.MediaPlayerHelper;
import org.hiucung.orangemusic.utils.BlurUtil;
import org.hiucung.orangemusic.utils.UpdateImage;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import me.bogerchan.niervisualizer.NierVisualizerManager;
import me.bogerchan.niervisualizer.renderer.IRenderer;
import me.bogerchan.niervisualizer.renderer.circle.CircleBarRenderer;

public class PlayerActivity extends AppCompatActivity {

    public static final int RESULT_CODE = 8848;//请求码用于intent

    int AUTO_SESSION_ID = 0;//mediaPlayer的autoseeeionid

    NierVisualizerManager visualizerManager;//音乐可视化组件

    SurfaceView playerSurfaceview;//可视化组件所依赖的surfaceView

    TextView playerSong,playerSinger,playerEndTime;
    TextView playerStartTime;

    ImageView playerBanner,playerBackground,mediaPlayerSong,backforward,
    playerMenu,favoriteSong,queueMusic,lastSong,nextSong;

    SeekBar songSeekBar;//进度条seekbar

    ArrayList<MusicBean> mDatas;//数据源

    boolean favoriteSongTag = true;//喜爱歌曲标志

    MediaPlayerHelper mediaPlayerHelper;

    int currnetPlayPosition = 0;//初始化播放的曲目为第0首

    int currnetPausePosition;//初始化暂停状态

    boolean isPlaySong = true;//初始化歌曲状态

    MusicBean musicBean;//musicBean设置为全局变量

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        transparentStatusBar();//透明状态栏方法

        //在需要启动的 activity 中开启动画的特征
        getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);

        setContentView(R.layout.activity_player);
        initView();

        mediaPlayerHelper = MediaPlayerHelper.getInstance(this);

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();

        //直接接收全部音乐数据和播放位置，保证两边切歌信息显示准确
        mDatas = (ArrayList<MusicBean>) bundle.getSerializable("mDatas");
        currnetPlayPosition = bundle.getInt("currnetPlayPosition");
        musicBean = mDatas.get(currnetPlayPosition);

        String path = musicBean.getPath();
        String musicSong = musicBean.getSong();
        String musicDuration = musicBean.getDuration();
        String musicSinger = musicBean.getSinger();

        AUTO_SESSION_ID = mediaPlayerHelper.getAudioSessionId();

        //更新频谱、音乐时长、背景模糊等
        updateMusicUI(path, musicSong, musicDuration, musicSinger, AUTO_SESSION_ID);

        //当从MainActivity切换过来时，判断需要改变是否播放的状态
        if (mediaPlayerHelper.isPlaying()){
            isPlaySong = false;
            mediaPlayerSong.setImageResource(R.drawable.ic_baseline_pause_24);
        }else {
            mediaPlayerSong.setImageResource(R.drawable.ic_play_circle_outline_black_24dp);
        }

        //PlayerActivity所有的点击监听事件
        buttonOnClickListener();

        //设置进度条更新TimerTask调度器
        TimerTask timerTask  = new TimerTask(){
            public void run(){
                if(mediaPlayerHelper.isPlaying()){//当歌曲播放的时候时间更新
                    updateTimer();
                }
            }
        };
        new Timer().scheduleAtFixedRate(timerTask,0,500);//固定码率运算，500毫秒执行一次

        getWindow().setEnterTransition(new Slide());//进入playerActivity时启动动画
    }

    /**
     * PlayerActivity所有的点击监听事件,按钮从左到右，从上到下，分别对应
     */
    private void buttonOnClickListener() {

        backforward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PlayerActivity.this,
                        MainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("currnetPlayPosition",currnetPlayPosition);
                intent.putExtras(bundle);
                setResult(RESULT_CODE,intent);
                finish();
            }
        });

        playerBanner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent intent = new Intent(PlayerActivity.this,
                        AlbumActivity.class);
                Bundle bundle = new Bundle();
                if (musicBean!=null) {
                    bundle.putSerializable("musicBean", musicBean);
                    intent.putExtras(bundle);
                }
                //配置跳转动画
                startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(PlayerActivity.this).toBundle());
                return true;
            }
        });

        favoriteSong.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (favoriteSongTag){
                    favoriteSong.setColorFilter(Color.CYAN);
                    favoriteSongTag = false;
                }else {
                    favoriteSong.setColorFilter(Color.WHITE);
                    favoriteSongTag = true;
                }
                return true;
            }
        });

        lastSong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currnetPlayPosition == 0) {
                    //已经是第一首
                    Toast.makeText(PlayerActivity.this, "已经是第一首音乐了啊TNT",
                            Toast.LENGTH_SHORT).show();
                }else {
                    currnetPlayPosition = currnetPlayPosition - 1;
                    musicBean = mDatas.get(currnetPlayPosition);
                    preparedMediaPlayer();
                    mediaPlayerSong.setImageResource(R.drawable.ic_baseline_pause_24);
                    visualizerManager.pause();
                    updateMusicUI(musicBean.getPath(),musicBean.getSong(),musicBean.getDuration(),musicBean.getSinger(),mediaPlayerHelper.getAudioSessionId());
                    isPlaySong =false;
                }
            }
        });

        mediaPlayerSong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayerHelper.isPlaying()){
                    mediaPlayerHelper.pause();
                    //暂停音乐把暂停位置得到
                    currnetPausePosition = mediaPlayerHelper.getCurrentPosition();
                    mediaPlayerSong.setImageResource(R.drawable.ic_play_circle_outline_black_24dp);

                }else {
                    //当音乐暂停之后再继续播放时不需要监听是否异步加载完成
                    mediaPlayerHelper.seekTo(currnetPausePosition);
                    mediaPlayerHelper.start();
                    mediaPlayerSong.setImageResource(R.drawable.ic_baseline_pause_24);
                }

                //这种情况属于没有点击歌曲列表，而直接进入了播放页点击播放按钮放歌的情况，需要重新传入参数更新UI
                if (isPlaySong){
                    preparedMediaPlayer();
                    mediaPlayerSong.setImageResource(R.drawable.ic_baseline_pause_24);
                    updateMusicUI(musicBean.getPath(),musicBean.getSong(),musicBean.getDuration(),musicBean.getSinger(),mediaPlayerHelper.getAudioSessionId());
                    isPlaySong =false;
                }
            }
        });

        nextSong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currnetPlayPosition == mDatas.size()-1) {
                    //已经是第一首
                    Toast.makeText(PlayerActivity.this, "已经是最后一首音乐了啊TNT", Toast.LENGTH_SHORT).show();
                }else {
                    currnetPlayPosition = currnetPlayPosition + 1;
                    musicBean = mDatas.get(currnetPlayPosition);
                    preparedMediaPlayer();
                    mediaPlayerSong.setImageResource(R.drawable.ic_baseline_pause_24);

                    updateMusicUI(musicBean.getPath(),musicBean.getSong(),musicBean.getDuration(),musicBean.getSinger(),mediaPlayerHelper.getAudioSessionId());
                    isPlaySong =false;
                }
            }
        });

        queueMusic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicListBottomDialog fragment = new MusicListBottomDialog();
                Bundle bundle = new Bundle();
                bundle.putSerializable("mDatas",mDatas);
                fragment.setArguments(bundle);//数据传递到fragment中

                fragment.show(getSupportFragmentManager(), "tag");
            }
        });

        songSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            //fromUser判断是否来自用户
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //按下进度条的时候，把进度传给MediaPlayer
                if(fromUser){
                    mediaPlayerHelper.seekTo(progress);
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //这个是当拖动的时候，当拖动的时候暂停音乐
                mediaPlayerHelper.pause();
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //当松开进度条的时候，播放音乐
                mediaPlayerHelper.start();
            }
        });
    }

    private void preparedMediaPlayer() {
        mediaPlayerHelper.setPath(musicBean.getPath());
        mediaPlayerHelper.setOnMeidaPlayerHelperListener(new MediaPlayerHelper.OnMeidaPlayerHelperListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mediaPlayerHelper.start();
            }

            @Override
            public void onCompletion(MediaPlayer mp) {

            }
        });
    }

    /**
     * 更新进度条进度和显示对应的时间
     */
    private void updateTimer(){
        runOnUiThread(() ->{//不用这个的话UI线程会报错
            int currentMs = mediaPlayerHelper.getCurrentPosition();
            int sec = currentMs / 1000;
            int min = sec / 60;
            sec -= min * 60;
            //格式化当前歌曲的进度时间
            String time = String.format("%02d:%02d", min, sec);
            //进度条更新
            songSeekBar.setProgress(currentMs);
            //进度时间刷新
            playerStartTime.setText(time);

        });
    }

    /***
     * 更新播放页面的所有UI视图
     * @param path
     * @param musicSong
     * @param musicDuration
     * @param musicSinger
     * @param auto_session_id
     */
    private void updateMusicUI(String path, String musicSong, String musicDuration, String musicSinger, int auto_session_id) {

        //获取📛mp3文件路径直接获取歌曲专辑bitmap
        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
        mediaMetadataRetriever.setDataSource(path);
        byte[] picture = null;
        picture = mediaMetadataRetriever.getEmbeddedPicture();

        //有的歌曲并没有专辑图，所以需要判空
        if(picture!=null) {
            //byte数组转换成位图
            Bitmap bytes2Bimap = Bytes2Bimap(picture);

            int bytes2BimapHeight = bytes2Bimap.getHeight()-1;

            //位图变圆
            Bitmap bm = UpdateImage.ClipSquareBitmap(bytes2Bimap, bytes2BimapHeight, bytes2BimapHeight);
            playerBanner.setImageBitmap(bm);

            //设置背景图
            //直接调用BlurUtil中的doBlur方法。3个参数在上述工具类代码中有详细注释
            Bitmap bgbm = BlurUtil.doBlur(bytes2Bimap, 20, 5);
            playerBackground.setImageBitmap(bgbm);
        }else {
            //播放页点击上一首下一首时，如果该歌曲没有专辑图片，需要设置默认的图片
            playerBanner.setImageResource(R.mipmap.audio_player_default_show_bg);
        }
        //设置歌手和歌名
        playerSong.setText(musicSong);
        playerSinger.setText(musicSinger);
        playerEndTime.setText(musicDuration);

        visualizerManager.release();//当每次选中新的歌曲item时，销毁框架实例，释放资源
        visualizerManager = new NierVisualizerManager();//音频可视化控件初始化
        if (auto_session_id != 0){
            visualizerManager.init(auto_session_id);//给visualizer传入autoSessionID
            visualizerManager.start(playerSurfaceview, new IRenderer[]{new CircleBarRenderer()});
        }

        int duration = mediaPlayerHelper.getDuration();
        //设置进度条的最大值是根据音乐的时间总长
        songSeekBar.setMax(duration);
    }

    /**
     * byte数组转换成位图
     * @param bitmap
     * @return
     */
    private Bitmap Bytes2Bimap(byte[] bitmap) {
        if (bitmap.length != 0) {
            return BitmapFactory.decodeByteArray(bitmap, 0, bitmap.length);
        } else {
            return null;
        }
    }

    private void initView() {
        //音频可视化控件初始化
        visualizerManager = new NierVisualizerManager();

        playerSurfaceview = findViewById(R.id.player_surfaceview);
        //SurfaceView设置透明背景
        playerSurfaceview.setZOrderOnTop(true);
        playerSurfaceview.getHolder().setFormat(PixelFormat.TRANSLUCENT);

        playerEndTime = findViewById(R.id.endTime);
        playerBanner = findViewById(R.id.player_iv_banner);
        playerSong = findViewById(R.id.player_tv_song);
        playerSinger = findViewById(R.id.player_tv_singer);
        playerBackground = findViewById(R.id.iv_background);
        mediaPlayerSong = findViewById(R.id.playsong);


        backforward = findViewById(R.id.top_iv_backforward);
        playerMenu = findViewById(R.id.top_iv_menu);
        favoriteSong = findViewById(R.id.iv_favorite_song);
        queueMusic = findViewById(R.id.iv_queue_music);
        lastSong = findViewById(R.id.lastsong);
        nextSong = findViewById(R.id.nextsong);

        songSeekBar = findViewById(R.id.songseek);

        playerStartTime = findViewById(R.id.startTime);
    }

    //拦截并重写返回建，不去销毁activity而是实现backforward按钮的功能
    @Override
    public void onBackPressed() {
        Intent intent = new Intent(PlayerActivity.this,
                MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("currnetPlayPosition",currnetPlayPosition);
        intent.putExtras(bundle);
        setResult(RESULT_CODE,intent);
        visualizerManager.stop();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        visualizerManager.pause();
    }

    private void transparentStatusBar() {
        //5.0 全透明实现
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //getWindow.setStatusBarColor(Color.TRANSPARENT)
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //4.4 全透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }
}